use crate::common::AppState;
use crate::error::AppError;
use crate::handler::file::files::upload_file;
use crate::handler::sse::sse_handler;
use crate::middleware::auth::auth_middleware;
use crate::openapi::OpenApiRouter;
use crate::{handler, AppConfig};
use axum::response::{Html, IntoResponse};
use axum::routing::{get, post};
use axum::{middleware, Router};
use http::Method;
use std::sync::Arc;
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;

const INDEX_HTML: &str = include_str!("../index.html");

pub async fn get_router(config: AppConfig) -> Result<Router, AppError> {
    let app_state = AppState::try_new(config).await?;
    let app_state = Arc::new(app_state);

    let cors = CorsLayer::new()
        // allow `GET` and `POST` when accessing the resource
        .allow_methods([
            Method::GET,
            Method::POST,
            Method::PUT,
            Method::DELETE,
            Method::OPTIONS,
            Method::PATCH,
            Method::HEAD,
            Method::TRACE,
        ])
        // allow requests from any origin
        .allow_origin(Any);
    let r = Router::new()
        .route("/events", get(sse_handler))
        .nest("/api", handler::api::router::get_router(app_state.clone()))
        .nest(
            "/chat",
            handler::chat::router::get_router(app_state.clone()),
        )
        .nest(
            "/message",
            handler::message::router::get_router(app_state.clone()),
        )
        .route("/upload", post(upload_file))
        .route("/sse", get(sse_handler))
        .layer(cors)
        .layer(TraceLayer::new_for_http())
        .layer(middleware::from_fn_with_state(
            app_state.clone(),
            auth_middleware, /* Arc<AppState> */
        ))
        .route("/", get(index_handler))
        .openapi()
        .with_state(app_state.clone());

    Ok(r)
}

async fn index_handler() -> impl IntoResponse {
    Html(INDEX_HTML)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handler::sse::sse_handler_old;
    use eventsource_stream::Eventsource;
    use std::path::PathBuf;
    use tokio::net::TcpListener;
    use tokio_stream::StreamExt as _;
    use tower_http::{services::ServeDir, trace::TraceLayer};

    #[tokio::test]
    async fn integration_test() {
        // A helper function that spawns our application in the background
        async fn spawn_app(host: impl Into<String>) -> String {
            let host = host.into();
            // Bind to localhost at the port 0, which will let the OS assign an available port to us
            let listener = TcpListener::bind(format!("{host}:0")).await.unwrap();
            // Retrieve the port assigned to us by the OS
            let port = listener.local_addr().unwrap().port();
            let assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets");
            let static_files_service =
                ServeDir::new(assets_dir).append_index_html_on_directories(true);
            // build our application with a route
            let router = Router::new()
                .fallback_service(static_files_service)
                .route("/sse", get(sse_handler_old))
                .layer(TraceLayer::new_for_http());

            tokio::spawn(async {
                axum::serve(listener, router).await.unwrap();
            });
            // Returns address (e.g. http://127.0.0.1{random_port})
            format!("http://{host}:{port}")
        }
        let listening_url = spawn_app("127.0.0.1").await;

        let mut event_stream = reqwest::Client::new()
            .get(format!("{listening_url}/sse"))
            .header("User-Agent", "integration_test")
            .send()
            .await
            .unwrap()
            .bytes_stream()
            .eventsource()
            .take(1);

        let mut event_data: Vec<String> = vec![];
        while let Some(event) = event_stream.next().await {
            match event {
                Ok(event) => {
                    // break the loop at the end of SSE stream
                    if event.data == "[DONE]" {
                        break;
                    }

                    event_data.push(event.data);
                }
                Err(_) => {
                    panic!("Error in event stream");
                }
            }
        }

        assert!(event_data[0] == "hi!");
    }
}
